import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../route/router.dart';
import 'test_batch_view_model.dart';

/// 考试批次:视图编辑
class TestBatchViewEdit extends StatefulWidget {
  final String? id;

  const TestBatchViewEdit({super.key, this.id});

  @override
  State<TestBatchViewEdit> createState() => _TestBatchViewEditState();
}

class _TestBatchViewEditState extends State<TestBatchViewEdit> {
  final formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<TestBatchViewModel>();
    model.loadInit(afterHandler: () => loadData(model));
  }

  ///加载数据
  void loadData(final TestBatchViewModel model) {
    final String id = widget.id ?? '';
    if (id.isEmpty) {
      model.cleanInputFields();
      return;
    }
    model.getInfoById(id);
  }

  String buildTitle() {
    final isAdd = (widget.id ?? '').isEmpty;
    return '${isAdd ? '新增' : '编辑'}${getRoteTitle(AppRote.testBatchEdit)}';
  }

  void popHandler(final bool ret) => context.pop<bool>(ret);

  void onSaveHandler(final TestBatchViewModel model) {
    if (formKey.currentState?.validate() ?? false) {
      final id = widget.id ?? '';
      if (id.isNotEmpty) {
        //修改处理
        model.onModifyHandler(id, () => popHandler(true));
        return;
      }
      //新增处理
      model.onAddHandler(() => popHandler(true));
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<TestBatchViewModel>(
        builder: (_, model, __) => ScaffoldPage.withPadding(
          header: PageHeader(title: Text(buildTitle())),
          content: buildForm(model),
          bottomBar: Padding(
            padding: EdgeInsetsDirectional.only(bottom: 20.h),
            child: OverflowBar(
              spacing: 2.w,
              children: [
                //保存
                buttons.save(onPressed: () => onSaveHandler(model)),
                //取消
                buttons.cancel(onPressed: () => popHandler(false)),
              ],
            ),
          ),
        ),
      );

  Widget buildForm(final TestBatchViewModel model) {
    final isAdd = (widget.id ?? '').isEmpty;
    Widget createContainer(Widget child) => Container(
          padding: EdgeInsetsDirectional.symmetric(vertical: 10.h),
          constraints: BoxConstraints(maxWidth: 268.w),
          child: child,
        );
    Widget createWidget(String label, Widget child) => createContainer(
          InfoLabel(
            label: label,
            child: child,
          ),
        );
    Widget createText(TestBatchInputField field) => createWidget(
          field.label,
          TextFormBox(
            controller: model.getController(field),
            placeholder: field.label,
            maxLines: field == TestBatchInputField.remark ? 3 : null,
            validator: (val) => field.validHandler(val),
          ),
        );
    Widget createSwitch() {
      final field = TestBatchInputField.status;
      final controller = model.getController(field);
      final child = ToggleSwitch(
        checked: () {
          final String val = controller?.text ?? '0';
          return (int.tryParse(val) ?? 0) == 1;
        }(),
        onChanged: (val) => setState(() => controller?.text = '${val ? 1 : 0}'),
      );
      return createWidget(field.label, child);
    }

    return Form(
      key: formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //学年学期
          createText(TestBatchInputField.semester),
          //年级
          createText(TestBatchInputField.grade),
          //名称
          createText(TestBatchInputField.name),
          //考试层次
          createText(TestBatchInputField.level),
          //学校
          createText(TestBatchInputField.schools),
          //备注
          createText(TestBatchInputField.remark),
          //状态
          if (!isAdd) createSwitch(),
        ],
      ),
    );
  }
}
